from twisted.internet import protocol, reactor, endpoints


class EchoServerDemo(protocol.Protocol):
    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.factory.numProtocols = self.factory.numProtocols + 1
        self.transport.write(
            "Welcome! There are currently %d open connections.\n" %
            (self.factory.numProtocols,))

    def connectionLost(self, reason):
        self.factory.numProtocols = self.factory.numProtocols - 1

    def dataReceived(self, data):
        self.transport.write(data)


class EchoFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return EchoServerDemo()


def _test_echo():
    """
    # TODO 未验证
    _test_echo()
    >
    192.168.1.103:8000
    """
    endpoints.serverFromString(reactor, "tcp:8000:interface=0.0.0.0").listen(EchoFactory())
    reactor.run()


if __name__ == '__main__':
    _test_echo()
